define([
    'require',
    'app.module',
    'treeview'
], function(require, app) {
    'use strict';

    app.controller('AgentCtrl', ['$scope', '$http', AgentCtrl]);

    function AgentCtrl($scope, $http) {
        $scope.list = list;
        $scope.agentAdapter = agentAdapter;

        // 查询代理商
        // list();

        function list() {
            $http.get('/raws/agents.json').then(function(response) {
                var _root = {
                    id: 0,
                    name: '根节点',
                    agents: response.data
                };

                var agents = [_root];
                $scope.agents = agents;
            }, function(err) {
                console.error(err);
            })
        }

        // 多级代理商适配函数
        function agentAdapter(nodes, agent) {
            var node = {};
            node.text = agent.name;
            // 根据代理商的属性，动态生成 href 属性
            // 如果是根节点，不能点击
            if (agent.id === 0) {
                node.href = 'javascript:void(0);';
            } else {
                node.href = '/agents/' + agent.id + '.json';
            }

            nodes.push(node);

            if (agent.agents && agent.agents.length > 0) {
                node.tags = [agent.agents.length];
                // 生成子节点
                node.nodes = [];

                // 遍历下级代理商适配子节点
                angular.forEach(agent.agents, function(agent) {
                    agentAdapter(node.nodes, agent);
                });
            }
        }
    }

    return {};
});